package com.stud.framework.runner;

import com.stud.common.constant.Constants;
import com.stud.common.core.domain.entity.SysUser;
import com.stud.common.core.domain.model.LoginUser;
import com.stud.common.jdbc.MyJdbcTemplate;
import com.stud.common.jdbc.SqlHelp;
import com.stud.framework.security.context.AuthenticationContextHolder;
import com.stud.framework.web.service.TokenService;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.core.annotation.Order;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Component;

import java.util.Objects;

/**
 * 开发环境初始化登陆用户,方便开发环境自测
 *
 * @author Stud
 */

@Component
@Order(1)
@Slf4j
public class DefaultLoginUserRunner implements ApplicationRunner {

    private static final String USERNAME = "admin";
    private static final String PASSWORD = "admin123";
    public static String TOKEN;

    @Resource
    private TokenService tokenService;
    @Resource
    private AuthenticationManager authenticationManager;
    @Resource
    private MyJdbcTemplate jdbcTemplate;
    @Value("${spring.profiles.active}")
    private String active;

    @Override
    public void run(ApplicationArguments args) {
        if (!Objects.equals("dev", active)) {
            return;
        }
        //如果是开发环境,则默认登陆配置账户,并且固定token,方面调试
        initUser(USERNAME, PASSWORD, "127.0.0.1", Constants.DEV_TOKEN);

    }

    private void initUser(String username, String password, String ip, String token) {
        String sql = " select user_id,dept_id from sys_user where user_name = ? ";
        SysUser sysUser = this.jdbcTemplate.find(SqlHelp.init(sql, username), SysUser.class);

        sysUser.setUserName(username);
        sysUser.setPassword(password);

        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(sysUser.getUserName(), sysUser.getPassword());
        AuthenticationContextHolder.setContext(authenticationToken);
        // 该方法会去调用 UserDetailsServiceImpl.loadUserByUsername
        Authentication authentication = authenticationManager.authenticate(authenticationToken);
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        loginUser.setIp(ip);

        TOKEN = tokenService.createToken(loginUser, token);
        log.info("====DEV====Authorization====" + username + "====");
        log.info(TOKEN);
    }

}
